/**
 * 文章编辑发布页面
 * @views {AddArticle}
 * @export {AddArticle}
*/

import React, { useState, useEffect } from 'react'
import { useNavigate, useLocation } from 'react-router-dom'
import style from './index.module.css'
import 'antd/dist/antd.css'
import { Row, Col, Input, Select, Button, message } from 'antd'
import axios from 'axios'
import { servicePath, get } from '@src/api/axios'
import markConfig from '@src/config/marked'
import { rTime } from '@src/utils/rTime'
import { marked } from 'marked'

const { Option } = Select
const { TextArea } = Input

export const AddArticle = () => {
  const [articleId, setArticleId] = useState(0)  // 文章id，0 表示新增0，非 0 表示修改
  const [articleTitle, setArticleTitle] = useState('')   // 文章标题
  const [articleContent, setArticleContent] = useState('')  // 文章编辑内容
  const [markdownContent, setMarkdownContent] = useState('预览内容') // 文章预览内容
  const [introduce, setIntroduce] = useState()  // 文章编辑简介
  const [introducehtml, setIntroducehtml] = useState('等待编辑') // 简介预览内容
  const [typeInfo, setTypeInfo] = useState([])  // 文章类别信息
  const [selectType, setSelectType] = useState(1)  // 选择的文章类别
  const [selectTypeName, setSelectTypeName] = useState('文章类型')

  const { navigate } = useNavigate() // 解构路由跳转方法
  const location = useLocation() // 获取路由中的参数

  markConfig // 支持markdown语法的配置

  // 文章内容 markdown 化
  const changeContent = (e) => {
    setArticleContent(e.target.value)
    let html = marked(e.target.value)
    setMarkdownContent(html)
  }

  // 文章介绍 markdown 化
  const changeIntroduce = (e) => {
    setIntroducemd(e.target.value)
    let html = marked(e.target.value)
    setIntroducehtml(html)
  }

  // 选择文章类型
  const changeselectType = value => {
    // console.log(value, 'vvvvvvvvvvv')
    setSelectType(value)
  }

  // 向中台请求获取文章类型的方法
  const getArticleType = () => {
    axios({
      method: 'GET',
      url: servicePath.getArticleType,
      // url: servicePath.getArticleType,
      header: { 'Access-Control-Allow-Origin': '*' }, // 配置请求头
      withCredentials: true // 是否携带凭证
    })
      .then(res => {
        console.log(res, '---------')
        if (res.data.data === '未登录') {
          navigate('/login')
        } else {
          setTypeInfo(res.data.data)
        }
      })
  }

  // 发布文章，将文章内容存进数据库
  const saveArticle = () => {
    if (!articleTitle) {
      message.error('文章标题不能为空')
    } else if (!typeInfo) {
      message.error('请选择文章类型')
    } else {
      message.success('文章保存成功')
    }

    // 设置请求体参数
    let dataProps = {
      type_id: selectType,
      title: articleTitle,
      article_content: articleContent,
      introduce: introducemd,
      addTime: rTime(new Date())
    }

    // articleId为0表示新增，要生成浏览次数
    if (articleId === 0) {
      dataProps.view_count = Math.floor(Math.random() * 500) + 500

      // 发起post请求，添加文章
      axios({
        method: 'post',
        url: servicePath.addArticle,
        data: dataProps,
        withCredentials: true
      }).then(
        res => {
          setArticleId(res.data.insertId)
          if (res.data.isScuccess) {
            message.success('文章保存成功')
          } else {
            message.error('文章保存失败')
          }
        }
      )
    } else {
      dataProps.id = articleId
      axios({
        method: 'post',
        url: servicePath.updataArticle,
        data: dataProps,
        withCredentials: true
      }).then(
        res => {
          if (res.data.isScuccess) {
            message.success('文章修改成功')
          } else {
            message.error('文章修改失败')
          }
        }
      )
    }
  }

  // 根据id获取文章
  const getArticleById = id => {
    setArticleId(id)
    get(`${servicePath.getArticleById}${id}`)
      .then(res => res.data.data[0])
      .then(data => {
        // console.log(data, '==============')
        setArticleTitle(data.title)
        setIntroduce(data.introduce)
        setIntroducehtml(marked(data.introduce))
        setArticleContent(data.article_content)
        setMarkdownContent(marked(data.article_content))
        setSelectType(data.typeId)
        setSelectTypeName(data.typeName)
      })
  }

  useEffect(() => {
    // 向中台请求文章类型数据
    getArticleType()
    // 判断是否接收到id参数，有参数则根据id请求文章详情
    if (location.state) {
      getArticleById(location.state.id)
    }
  }, [])

  useEffect(() => {
    changeselectType(selectType)
  }, [selectType])

  return (
    <>
      <Col span={12}>
        {/* <Row>
          <Col span={24}> */}
        <Button size="middle">保存文章</Button>
        <Button
          type="primary"
          onClick={saveArticle}
          size="middle">发布文章</Button>
        <br />
        <br />
        {/* </Col>
        </Row> */}
      </Col>
      <Row gutter={5}>
        <Col span={18}>
          <Row gutter={10}>
            <Col span={20}>
              <Input
                placeholder="博客标题"
                size="middle"
                className={style.input_title}
                onChange={e => { setArticleTitle(e.target.value) }}
                value={articleTitle}
              />
            </Col>
            <Col span={4}>
              &nbsp;
              <Select
                defaultValue={selectTypeName}
                size="middle"
                onChange={changeselectType}
              >
                {typeInfo.map((item, index) => <Option key={item.Id + index} value={item.Id}>
                  {item.typeName}
                </Option>
                )}
              </Select>
            </Col>
          </Row>
          <br />
          <Row gutter={10}>
            <Col span={24}>
              <br />
              <TextArea
                rows={4}
                placeholder="文章简介"
                onChange={changeIntroduce}
                onPressEnter={changeIntroduce}
                value={introduce}
              />
              <div
                className={style.introduce_html}
                dangerouslySetInnerHTML={{ __html: `文章简介: ${introducehtml}` }} >
              </div>
              <br /><br />
              <div className="introduce-html"></div>
            </Col>
            <Col span={12}>
              <TextArea
                className={style.markdown_content}
                rows={35}
                placeholder="文章内容"
                onChange={changeContent}
                onPressEnter={changeContent}
                value={articleContent}
              />
            </Col>
            <Col span={12}>
              <div
                className={style.show_html}
                dangerouslySetInnerHTML={{ __html: markdownContent }}
              ></div>
            </Col>
          </Row>
        </Col>
        {/* <Col span={6}>sadfsadf</Col> */}
      </Row>
    </>
  )
}
